package com.ns.dcjh;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bytedance.sdk.open.douyin.DouYinOpenApiFactory;
import com.bytedance.sdk.open.douyin.DouYinOpenConfig;
import com.ns.dcjh.constant.Constant;
import com.ns.dcjh.utils.CrashHandler;
import com.ns.dcjh.utils.SharedPreferencesUtils;
import com.ns.dcjh.utils.ToastUtils;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.api.utils.JCollectionAuth;
import cn.jpush.android.api.JPushInterface;
import xcrash.ICrashCallback;
import xcrash.XCrash;

public class MyApplication extends Application {
    //app
    private static MyApplication mApp;
    //活动数组
    private static List<Activity> activityList;

    //微信分享图片
    private ArrayList<String> wxShareImageList;

    public static MyApplication getInstance() {
        if (mApp == null) {
            mApp = new MyApplication();
        }
        return mApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mApp = this;
        activityList = new ArrayList<>();
        wxShareImageList = new ArrayList<>();

        initLogger();

        registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);

        //打开错误日志，保存到sd卡
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);

//        PackageManager.getInstance().init(getApplicationContext());
    }

    //初始化第三方SDK，隐私合规，在用户同意隐私协议后再调用
    public void initThirdSdk() {
        Log.d("xuezeyuan", "三方sdk初始话");
        initJPush();
        initUmeng();
        initX5();
    }

    //Logger初始化
    private void initLogger() {
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }

    //极光推送初始化
    private void initJPush() {
        JCollectionAuth.enableAutoWakeup(this, false);  //禁止自启动
        JCollectionAuth.setAuth(this, true);
        JPushInterface.setDebugMode(BuildConfig.DEBUG); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush

        //保存registration id 到本地
        String regId = JPushInterface.getRegistrationID(this);
        if (StringUtils.isNotEmpty(regId)) {
            SharedPreferencesUtils.getInstance(this).setObject(Constant.SP_KEY_REGISTRATION_ID, regId);
        }
        Logger.d("JPush registration-id : " + regId);
        Logger.d("JPush registration-id sp : " + SharedPreferencesUtils.getInstance(this).objectForKey(Constant.SP_KEY_REGISTRATION_ID, ""));
    }

    //友盟初始化
    private void initUmeng() {
        UMConfigure.preInit(
                this,
                Constant.UMENG_APP_ID,
                "umeng"
        );

        UMConfigure.init(
                this,
                Constant.UMENG_APP_ID,
                "umeng",
                UMConfigure.DEVICE_TYPE_PHONE,
                ""
        );
        PlatformConfig.setWeixin(Constant.WECHAT_APP_ID, Constant.WECHAT_APP_SECRET);
        PlatformConfig.setWXFileProvider(Constant.FILE_PROVIDER_NAME);
        UMConfigure.setLogEnabled(true);
    }

    //抖音初始化
    public void initDouYin() {
        if(!DouYinOpenApiFactory.init(new DouYinOpenConfig(Constant.DOUYIN_CLIENT_KEY))) {
            ToastUtils.info(mApp, "抖音初始化失败");
        };
    }

    //x5初始化
    @SuppressLint("HardwareIds")
    private void initX5() {
        QbSdk.setDownloadWithoutWifi(true);
        Bundle bundle = new Bundle();
        bundle.putString("model", Build.MODEL);
        bundle.putString("serial", Build.SERIAL);
        QbSdk.setUserID(this, bundle);
        QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                Logger.d("X5 Core Init Finished");
            }

            @Override
            public void onViewInitFinished(boolean b) {
                Logger.d("X5 View Init Finished:" + b);
            }
        });

        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
                Logger.d("X5 Download Finish");
            }

            @Override
            public void onInstallFinish(int i) {
                Logger.d("X5 Install Finish");
            }

            @Override
            public void onDownloadProgress(int i) {
                Logger.d("X5 Installing Process : " + i);
            }
        });
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        ICrashCallback callback = new ICrashCallback() {
            @Override
            public void onCrash(String logPath, String emergency) {
                    new Thread() {
                        public void run() {
                            try {
                                Looper.prepare();
                                SharedPreferencesUtils.getInstance(getApplicationContext()).setObject(Constant.SP_KEY_PREVIOUS_CRASH, logPath);
                                Looper.loop();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
            }
        };
        XCrash.init(this,new XCrash.InitParameters()
                .setJavaRethrow(true)
                .setJavaLogCountMax(10)
//                .setJavaDumpAllThreadsWhiteList(new String[]{"^main$", "^Binder:.*", ".*Finalizer.*"})
                .setJavaDumpAllThreadsCountMax(10)
                .setJavaCallback(callback)
                .setNativeRethrow(true)
                .setNativeLogCountMax(10)
//                .setNativeDumpAllThreadsWhiteList(new String[]{"^xcrash\\.sample$", "^Signal Catcher$", "^Jit thread pool$", ".*(R|r)ender.*", ".*Chrome.*"})
                .setNativeDumpAllThreadsCountMax(10)
                .setNativeCallback(callback)
                .setPlaceholderCountMax(3)
                .setPlaceholderSizeKb(512)
                .setLogFileMaintainDelayMs(1000));
    }

    //Activity生命周期回调
    private final ActivityLifecycleCallbacks mActivityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
            Logger.d("onActivityCreated: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            Logger.d("onActivityStarted: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            Logger.d("onActivityResumed: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            Logger.d("onActivityPaused: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
            Logger.d("onActivityStopped: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            Logger.d("onActivitySaveInstanceState: " + activity.getComponentName().getClassName());
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
            Logger.d("onActivityDestroyed: " + activity.getComponentName().getClassName());
        }
    };

    /**
     * 添加activity到list中
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (activityList != null && activity != null && !activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    /**
     * 退出list中的所有activity
     */
    public void quitAllActivity() {
        if (activityList != null && !activityList.isEmpty()) {
            for (Activity a : activityList) {
                a.finish();
            }
            activityList.clear();
        }
    }

    /**
     * 退出单个activity
     * @param activity
     */
    public void quitActivity(Activity activity) {
        if (activityList != null && !activityList.isEmpty() && activityList.contains(activity)) {
            activityList.remove(activity);
            activity.finish();
        }
    }

    /**
     * 清空list中的activity
     */
    public void clearAllActivity() {
        if (activityList != null && !activityList.isEmpty()) {
            activityList.clear();
        }
    }

    public ArrayList<String> getWxShareImageList() {
        return wxShareImageList;
    }

    public void clearWxShareImageList() {
        this.wxShareImageList.clear();
    }
}
